/*
 * Copyright (c) 2015. 石头哥哥
 */

package com.comom.manager.kit;

import com.comom.manager.model.User;
import com.comom.manager.model.vo.ObjectVo;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author 石头哥哥
 *         </P>
 *         Date:   2015/7/23
 *         </P>
 *         Time:   15:24
 *         </P>
 *         Package: mengchongdoc
 *         </P>
 *         <p/>
 *         注解： 基于jackson mapper获取
 *         <p/>
 *         ObjectMapperFactory  默认是单例
 */
@Service
public class ObjectMapperFactory {

    /**
     * 记录序列化失败异常
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectMapperFactory.class);

    /**
     * json object mapper
     * thread safe !
     */
    private static final ObjectMapper mapper = new ObjectMapper();


    /**
     * 初始化mapper 以支持json中中文字符转化为unicode
     */
    @PostConstruct
    private void initMapper() {
        mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    }


    /**
     * 转化json字符串
     *
     * @param objectVo       数据构建对象
     * @return
     */
    public String writeValueAsString(ObjectVo objectVo) {
        try {
            return mapper.writeValueAsString(objectVo);
        } catch (JsonProcessingException e) {
            LOGGER.error("object:" + objectVo + " 序列化json失败->" + e.getMessage());
            return null;
        }
    }


    /**
     *
     * @param args
     */
    public static void  main(String[]args){
        ObjectMapper mapper = new ObjectMapper();
        mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
        User user=new User();
        user.setNickname("xaw+x测试实施");
        try {
            System.out.println(mapper.writeValueAsString(user));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}
